package com.cxh.rmsq.ui.fragment.self

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.TimeUtils
import com.cxh.rmsq.R
import com.cxh.rmsq.db.model.CommunityContent
import com.cxh.rmsq.db.model.HuntBean
import com.cxh.rmsq.db.model.JoinRecord
import com.cxh.rmsq.im.IMManager
import com.cxh.rmsq.net.newNet.TreasureViewModel
import com.cxh.rmsq.ui.adapter.self.CircleListAdapter
import com.cxh.rmsq.ui.adapter.self.JoinRecordListAdapter
import com.cxh.rmsq.ui.fragment.BaseFragment
import com.cxh.rmsq.utils.dialog.JoinTimeSelectPopup
import com.lxj.xpopup.XPopup
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.MaterialHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener

private const val ARG_PARAM1 = "param1"


class JoinRecordFragment : BaseFragment(), JoinRecordListAdapter.OnCustomClickListener {
    private var param1: Int? = 0 //1已完成 0未完成
    private var page = 1
    private var clueId = ""
    private lateinit var refreshList: SmartRefreshLayout
    private lateinit var recyclerView: RecyclerView
    private lateinit var sll_date: LinearLayout
    private lateinit var tv_time: TextView
    private lateinit var iv_arrow: ImageView
    private var listAdapter: JoinRecordListAdapter? = null

    private val viewModel by lazy {
        ViewModelProvider.NewInstanceFactory().create(TreasureViewModel::class.java)
    }

    companion object {
        fun newInstance(param1: Int): JoinRecordFragment {
            val fragment = JoinRecordFragment()
            val args = Bundle()
            args.putInt(ARG_PARAM1, param1)
            fragment.arguments = args
            return fragment
        }
    }

    override fun getLayoutResId(): Int {
        return R.layout.fragment_join_record
    }

    override fun onInitView(savedInstanceState: Bundle?, intent: Intent?) {

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        param1 = requireArguments().getInt(ARG_PARAM1)

        refreshList = view.findViewById(R.id.refresh_list) as SmartRefreshLayout
        recyclerView = view.findViewById(R.id.rv_list) as RecyclerView
        sll_date = view.findViewById(R.id.sll_date) as LinearLayout
        tv_time = view.findViewById(R.id.tv_time) as TextView
        iv_arrow = view.findViewById(R.id.iv_arrow) as ImageView

        recyclerView.layoutManager = LinearLayoutManager(context)
        listAdapter = JoinRecordListAdapter(param1!!, this) //1已完成 0未完成
        listAdapter!!.setEmptyView(View.inflate(activity, R.layout.empty_data_layout, null))
        recyclerView.adapter = listAdapter

        refreshList.resetNoMoreData()
        refreshList.setRefreshHeader(MaterialHeader(activity))
        refreshList.setRefreshFooter(ClassicsFooter(activity))
        refreshList.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                page++
                onResume()
                refreshLayout.finishLoadMore()
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                page = 1
//                dataList.clear()
                listAdapter!!.setNewInstance(null)
                onResume()
            }
        })

    }

    var arrayList = mutableListOf<String>()

    override fun onResume() {
        super.onResume()
        page = 1
        listAdapter!!.setNewInstance(null)

        if (1 == param1) {//1已完成 0未完成
            sll_date.isVisible = true
            viewModel.getHuntTimeList {
                if (it.data != null && it.code == 200) {
                    if (it.data.size > 0) {
                        arrayList.clear()
                        for (i in it.data) {
                            arrayList.add(
                                i.name + "  " + TimeUtils.millis2String(
                                    i.startDate, "yyyy-MM-dd"
                                ) + "~" +
                                        TimeUtils.millis2String(i.endDate, "yyyy-MM-dd")
                            )
                        }
                        clueId = it.data[0].id.toString()
                        tv_time.text = it.data[0].name + "  " + TimeUtils.millis2String(
                            it.data[0].startDate, "yyyy-MM-dd"
                        ) + "~" +
                                TimeUtils.millis2String(it.data[0].endDate, "yyyy-MM-dd")

                        getData2()
                        sll_date.setOnClickListener {
                            XPopup.Builder(context)
//                .dismissOnTouchOutside(false)
                                .dismissOnBackPressed(false)
                                .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                                .atView(sll_date)
                                .borderRadius(6f)
                                /*.maxHeight(((XPopupUtils.getAppHeight(context) * 1f).toInt()))*/
                                .asCustom(
                                    JoinTimeSelectPopup(
                                        requireContext(),
                                        2, tv_time.text.toString(),
                                        arrayList,
                                        object : JoinTimeSelectPopup.onClick {
                                            override fun click(
                                                s: Int,
                                                s1: String,
                                                s2: String,
                                                s3: String,
                                                s4: String
                                            ) {
                                                tv_time.text = s1
                                                onResume()
                                            }
                                        })
                                )
                                .show()
                        }
                    }
                }
            }
        } else {
            sll_date.isVisible = false
            clueId = ""
            getData()
        }
    }

    private fun getData() {
        viewModel.getExchangeRecords(
            param1!!, page, 10
        ) {
            Log.e("total", it.data.total.toString() + "")
            if (refreshList.isRefreshing) {
                refreshList.finishRefresh()
            }
            if (it.data != null) {
                if (page == 1) {
                    listAdapter!!.setNewInstance(it.data.list)
                    if (it.data.list!!.size < 10) {
                        refreshList.setEnableLoadMore(false)
                    } else {
                        refreshList.setEnableLoadMore(true)
                    }
                } else {
                    if (it.data.list!!.size > 0) {
                        listAdapter!!.addData(it.data.list!!)
                        refreshList.setEnableLoadMore(true)
                    } else {
                        refreshList.setEnableLoadMore(false)
                        refreshList.finishLoadMoreWithNoMoreData()
                    }
                }

                listAdapter!!.notifyDataSetChanged()
            }
        }
    }

    private fun getData2() {
        viewModel.getExchangeRecords2(
            param1!!, clueId, page, 10
        ) {
            Log.e("total", it.data.total.toString() + "")
            if (refreshList.isRefreshing) {
                refreshList.finishRefresh()
            }
            if (it.data != null) {
                if (page == 1) {
                    listAdapter!!.setNewInstance(it.data.list)
                    if (it.data.list!!.size < 10) {
                        refreshList.setEnableLoadMore(false)
                    } else {
                        refreshList.setEnableLoadMore(true)
                    }
                } else {
                    if (it.data.list!!.size > 0) {
                        listAdapter!!.addData(it.data.list!!)
                        refreshList.setEnableLoadMore(true)
                    } else {
                        refreshList.setEnableLoadMore(false)
                        refreshList.finishLoadMoreWithNoMoreData()
                    }
                }

                listAdapter!!.notifyDataSetChanged()
            }
        }
    }

    override fun onItemClick(position: Int, data: JoinRecord?) {

    }

    override fun onItemLongClick(position: Int, data: JoinRecord?) {

    }
}